package com.apadog.study.video.service;

import com.apadog.study.utils.RestTemplateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class DyService {

    private static RestTemplate restTemplate = RestTemplateUtil.getInstance();

    private final static HttpHeaders headers = new HttpHeaders();

    public DyService() {
        headers.set("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0");
        headers.set("Origin","https://www.douyin.com");
        headers.set("Referer","https://www.douyin.com/");

    }

    /**
     * 解析抖音视频/图集
     */
    public Map<String, Object> parseDouyin(String url) {
        try {
            // 1. 提取视频ID
            String id = extractId(url);
            if (id == null) {
                return createResponse(400, "无法解析视频ID", null);
            }

            // 2. 获取视频信息
            String videoUrl = id;
            ResponseEntity<String> response = restTemplate.exchange(
                    videoUrl,
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class
            );

            // 3. 提取视频信息
            String html = response.getBody();
            Pattern pattern = Pattern.compile("window\\._ROUTER_DATA\\s*=\\s*(.*?)\\</script>", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(html);

            if (!matcher.find()) {
                return createResponse(201, "解析失败", null);
            }

            ObjectMapper objectMapper = new ObjectMapper();
            // 4. 解析JSON数据
            JsonNode videoInfo = objectMapper.readTree(matcher.group(1));
            if (!videoInfo.has("loaderData")) {
                return createResponse(201, "解析失败", null);
            }

            // 5. 提取视频信息
            JsonNode itemList = videoInfo.get("loaderData").get("video_(id)/page").get("videoInfoRes").get("item_list").get(0);

            // 6. 处理视频URL
            String videoResUrl = itemList.get("video").get("play_addr").get("url_list").get(0).asText()
                    .replace("playwm", "play");

            // 7. 处理图片URL
            List<String> imgUrls = new ArrayList<>();
            JsonNode images = itemList.get("images");
            if (images != null && images.isArray()) {
                for (JsonNode image : images) {
                    if (image.has("url_list") && image.get("url_list").isArray() && image.get("url_list").size() > 0) {
                        imgUrls.add(image.get("url_list").get(0).asText());
                    }
                }
            }

            // 8. 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("author", itemList.get("author").get("nickname").asText());
            data.put("uid", itemList.get("author").get("unique_id").asText());
            data.put("avatar", itemList.get("author").get("avatar_medium").get("url_list").get(0).asText());
            data.put("like", itemList.get("statistics").get("digg_count").asText());
            data.put("time", itemList.get("create_time").asText());
            data.put("title", itemList.get("desc").asText());
            data.put("cover", itemList.get("video").get("cover").get("url_list").get(0).asText());
            data.put("images", imgUrls);
            data.put("url", !imgUrls.isEmpty() ?
                    "当前为图文解析，图文数量为:" + imgUrls.size() + "张图片" :
                    videoResUrl);

            // 9. 处理音乐信息
            Map<String, Object> music = new HashMap<>();
            music.put("title", itemList.get("music").get("title").asText());
            music.put("author", itemList.get("music").get("author").asText());
            music.put("avatar", itemList.get("music").get("cover_large").get("url_list").get(0).asText());
            music.put("url", itemList.get("video").get("play_addr").get("uri").asText());
            data.put("music", music);

            return createResponse(200, "解析成功", data);

        } catch (Exception e) {
            return createResponse(500, "解析失败: " + e.getMessage(), null);
        }
    }

    /**
     * 提取视频ID
     */
    private String extractId(String url) {
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class
            );

            String location = response.getHeaders().getFirst("Location");
            if (location == null) {
                location = url;
            }

//            Pattern pattern = Pattern.compile("[0-9]+|(?<=video/)[0-9]+");
//            Matcher matcher = pattern.matcher(location);
//            if (matcher.find()) {
//                return matcher.group();
//            }
//            return null;
            return location;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 创建响应数据
     */
    private Map<String, Object> createResponse(int code, String msg, Map<String, Object> data) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("msg", msg);
        response.put("data", data);
        return response;
    }

    // 使用示例
    public static void main(String[] args) throws JsonProcessingException {
        DyService parser = new DyService();
        String url = "5.69 wsE:/ 09/15 g@O.KW 最适合我拍的视频出现了# 记录猫咪日常 # 我的猫咪 # 家有傻猫 # 我和我的喵 # 宠物vlog  https://v.douyin.com/cRwoLC6G7R8/ 复制此链接，打开Dou音搜索，直接观看视频！"; // 替换为实际的抖音分享链接
        // 提取短链接
        Pattern linkPattern = Pattern.compile("https://v\\.douyin\\.com/\\S+?/");
        Matcher linkMatcher = linkPattern.matcher(url);
        String videoLink = linkMatcher.find() ? linkMatcher.group() : "";
        if(StringUtils.isBlank(videoLink)){
            throw  new RuntimeException("未解析到视频连接");
        }
        Map<String, Object> result = parser.parseDouyin(videoLink);
        System.out.println(new ObjectMapper().writeValueAsString(result));
    }
}
